package month5.day11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Server {
    public static void startupServer(int port) throws IOException {
        ServerSocket ss = new ServerSocket(port);
        while (true) {
            Socket s = ss.accept();
            new Thread(new ServerThreadHandler(s)).start();
        }
    }

    public static void main(String[] args) {
        try {
            startupServer(18080);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //内部类实现多线程   每当一个客户端成功与服务器建立连接，开启一个新的线程服务
    private static class ServerThreadHandler implements Runnable {
        private final Socket socket;

        //带参构造方法
        public ServerThreadHandler(final Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            BufferedReader bf = null;
            PrintStream ps=null;
            try {
                bf = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
                ps = new PrintStream(socket.getOutputStream(), true);
                //服务器端读取客户端发送过来的数据
                while (true) {
                    String msg = bf.readLine();

                    String message = null;
                    if (msg.equals("气温")) {
                        message = "气温20°";
                    } else if (msg.equals("风力")) {
                        message = "风力三级";
                    } else if (msg.equals("pm2.5")) {
                        message = "pm2.5为45";
                    } else if (msg.equals("湿度")) {
                        message = "湿度中毒";
                    }else if(msg.equals("exit")){
                        message="exit";
                    }

                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    ps.println(message + sdf.format(date));
                }
            } catch (IOException e) {
                try {
                    bf.close();
                    ps.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

            }

        }
    }
}
